﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Lion.WeiXin.Tools.Log;
using Senparc.Weixin;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.MessageHandlers;
using Senparc.Weixin.Context;
using System.IO;
using Lion.WeiXin.Core;
using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Core.Models;
using System.Web.Script.Serialization;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.CommonAPIs;
namespace Lion.WeiXin.Handler
{
    public class CustomMessageHandler : MessageHandler<MessageContext<IRequestMessageBase, IResponseMessageBase>>
    {

        IWeChatUser iwcUser = new WeChatUserDAO();
        DBContext db = new DBContext();

        public CustomMessageHandler(Stream inputStream) : base(inputStream) { }

        //当无消息匹配时，默认回复消息
        public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
        {
            var responseMessage = this.CreateResponseMessage<ResponseMessageText>();//ResponseMessageText也可以是News等其他类型
            responseMessage.Content = "消息已经收到，感谢您的参与！";
            return responseMessage;
        }
        /// <summary>
        /// 用户关注请求 
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            LogHelper.Info("欢迎新用户{0}关注我们，我们将为你提供最优质的服务！ ", requestMessage.FromUserName);
            // 1 用户关注，加入本地数据库           
            //获取用户信息 
            string appid = Lion.WeiXin.Core.Models.Config.AppId;
            string access_token = AccessTokenContainer.TryGetToken(appid, Lion.WeiXin.Core.Models.Config.AppSecret);
            UserInfoJson wxUser = new UserInfoJson();
            try
            {
                if (!iwcUser.Exists(requestMessage.FromUserName))
                {
                    wxUser = User.Info(access_token, requestMessage.FromUserName);
                    WeChatUserModel model = new WeChatUserModel();
                    model.OpenId = wxUser.openid;
                    model.NickName = wxUser.nickname;
                    model.HeadPicture = wxUser.headimgurl;
                    model.Sex = wxUser.sex;
                    model.City = wxUser.city;
                    model.Province = wxUser.province;
                    model.Dic_UserGroup = 27;  //新关注默认未分组用户
                    model.IsSubscribe = wxUser.subscribe;
                    model.Subscribe_Date = model.ConvertIntToDate(wxUser.subscribe_time);
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "用户{0} 本地数据保存失败!", requestMessage.FromUserName);
            }

            ResponseMessageText responseMessage = CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = string.Format("热烈欢迎新朋友：{0} ", wxUser.nickname);

            return responseMessage;
            // return base.OnEvent_SubscribeRequest(requestMessage);
        }

        /// <summary>
        /// 取消关注事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage)
        {
            //删除本地用户
            iwcUser.DeleteUser(requestMessage.FromUserName);

            return base.OnEvent_UnsubscribeRequest(requestMessage);
        }
        /// <summary>
        /// 文本自动回复
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "";
            if (string.IsNullOrEmpty(requestMessage.Content))
            {
                return responseMessage;
            }
            //去除特殊字符
            string reqMsg = Tools.StringHelper.ReplaceWebStr(requestMessage.Content);
            Lion.WeiXin.Tools.Log.LogHelper.Info("OnTextRequest:reqMsg={0}", reqMsg);
            //匹配关键字，只执行满足条件第一个
            Lion.WeiXin.Tools.Log.LogHelper.Info("开始文本:reqMsg={0}", reqMsg);
            string where = string.Format("Keyword like '{0}%' and ActionType='{1}'", reqMsg, AutoReplyEnum.文本动作.ToString());
            AutoReplyModel rule = db.AutoReplys.GetList(1, where, "Sequence").FirstOrDefault();
            if (rule != null)
            {
                //第一个回复有效
                if (!string.IsNullOrEmpty(rule.ReplyMsg))
                {
                    responseMessage.Content = rule.ReplyMsg;
                    return responseMessage;
                }
                if (!string.IsNullOrEmpty(rule.DoTask))
                {
                    string replyMsg = (string)CustomTask.Execute(rule.DoTask, requestMessage.FromUserName);
                    responseMessage.Content = replyMsg;
                    return responseMessage;
                }
            }
            Lion.WeiXin.Tools.Log.LogHelper.Info("结束文本:reqMsg={0}", reqMsg);
            //执行任意指令动作
            Lion.WeiXin.Tools.Log.LogHelper.Info("开始处理任意指令:reqMsg={0}", reqMsg);
            where = string.Format("ActionType='{1}'", reqMsg, AutoReplyEnum.任意指令.ToString());
            List<AutoReplyModel> replys = db.AutoReplys.GetList(where).OrderBy(n => n.Sequence).ToList();
            foreach (AutoReplyModel curRule in replys)
            {
                string replyMsg = (string)CustomTask.Execute(curRule.DoTask, requestMessage.FromUserName, reqMsg);
                //为空，跳过，执行下一个动作
                Lion.WeiXin.Tools.Log.LogHelper.Info("开始处理任意指令:replyMsg={0}", replyMsg);
                if (!string.IsNullOrEmpty(replyMsg))
                {
                    responseMessage.Content = replyMsg;
                    return responseMessage;
                }
            }
            Lion.WeiXin.Tools.Log.LogHelper.Info("结束处理任意指令:reqMsg={0}", reqMsg);
            //默认回复
            return base.OnTextRequest(requestMessage);

        }
        /// <summary>
        /// 语音自动回复，
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "";
            LogHelper.Info("语音文本{0}", requestMessage.Recognition);
            if (string.IsNullOrEmpty(requestMessage.Recognition))
            {
                return responseMessage;
            }
            string reqMsg = Tools.StringHelper.ReplaceWebStr(requestMessage.Recognition);
            string where = string.Format("Keyword like '{0}%' and ActionType='{1}'", reqMsg, AutoReplyEnum.语音动作.ToString());
            List<AutoReplyModel> reMsgs = db.AutoReplys.GetList(where);
            if (reMsgs.Count > 0)
            {
                AutoReplyModel rule = reMsgs[0];
                //第一个回复有效
                if (!string.IsNullOrEmpty(rule.ReplyMsg))
                {
                    responseMessage.Content = rule.ReplyMsg;
                    return responseMessage;
                }
                if (!string.IsNullOrEmpty(rule.DoTask))
                {
                    string replyMsg = (string)CustomTask.Execute(rule.DoTask, requestMessage.FromUserName);
                    responseMessage.Content = replyMsg;
                    return responseMessage;
                }

                //无配置，也不响应
                return responseMessage;
            }
            else
            {
                //默认回复
                return base.OnVoiceRequest(requestMessage);
            }
        }

        /// <summary>
        /// Click 类型菜单功能
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            var responseMessage = CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "";
            if (string.IsNullOrEmpty(requestMessage.EventKey))
            {
                return responseMessage;
            }
            string reqMsg = Tools.StringHelper.ReplaceWebStr(requestMessage.EventKey.ToLower());
            string where = string.Format("Keyword = '{0}' and ActionType='{1}'", reqMsg, AutoReplyEnum.菜单动作.ToString());
            List<AutoReplyModel> reMsgs = db.AutoReplys.GetList(where);
            if (reMsgs.Count > 0)
            {
                AutoReplyModel rule = reMsgs[0];
                //第一个回复有效
                if (!string.IsNullOrEmpty(rule.ReplyMsg))
                {
                    responseMessage.Content = rule.ReplyMsg;
                    return responseMessage;
                }
                if (!string.IsNullOrEmpty(rule.DoTask))
                {
                    string replyMsg = (string)CustomTask.Execute(rule.DoTask, requestMessage.FromUserName);
                    responseMessage.Content = replyMsg;
                    return responseMessage;
                }

                //无配置，也不响应
                return responseMessage;
            }
            else
            {
                //无配置，不响应
                return responseMessage;
            }

        }


        /// <summary>
        /// 链接类型菜单 View 类型
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ViewRequest(RequestMessageEvent_View requestMessage)
        {
            LogHelper.Info("接收用户{0}访问链接{1}！ ", requestMessage.FromUserName, requestMessage.EventKey);

            return base.OnEvent_ViewRequest(requestMessage);
        }

        public override void OnExecuting()
        {

            LogHelper.Info("接收请求:msgType={0},FromUserName={1},ToUserName={2},CreateTime={3},MsgId={4}", base.RequestMessage.MsgType.ToString(), RequestMessage.FromUserName, RequestMessage.ToUserName, RequestMessage.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"), RequestMessage.MsgId);
            base.OnExecuting();

        }

    }
}